package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"videos/model/mysql"
	"videos/pkg"

	"videos/videorpc/internal/svc"
	"videos/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *videorpc.RegisterRequest) (*videorpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	err := user.FindUserByMobiles(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}

	if user.ID != 0 {
		return nil, errors.New("该用户已注册,可直接登录")
	}

	user = mysql.User{
		Mobile:    in.Mobile,
		Password:  pkg.Md5(in.Password),
		NickName:  fmt.Sprintf("游客_%d", rand.Intn(9000)),
		HeadImage: "https://ts1.tc.mm.bing.net/th/id/OIP-C.-rBqkricrrEXBZsFzjxtlQAAAA?cb=ucfimgc2&rs=1&pid=ImgDetMain&o=7&rm=3",
	}

	err = user.Register(mysql.DB)
	if err != nil {
		return nil, err
	}

	return &videorpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
